<?php
class ControllerModulePageBuilder extends Controller {
	private $error = array(); 
	
	public function index() {   
		$this->language->load('module/pagebuilder');

		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('design/layout');
		
  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_module'),
			'href'      => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
		
   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('module/pagebuilder', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);

		if (isset($this->session->data['error'])) {
			$this->data['error'] = $this->session->data['error'];
		
			unset($this->session->data['error']);
		} else {
			$this->data['error'] = '';
		}

		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];
		
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}
		
		$this->data['action'] = $this->url->link('module/pagebuilder', 'token=' . $this->session->data['token'], 'SSL');
		
		$this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');

		$this->data['token'] = $this->session->data['token'];
		
		$this->data['restore'] = $this->url->link('module/pagebuilder/restore', 'token=' . $this->session->data['token'], 'SSL');

		$this->data['layouts'] = $this->model_design_layout->getLayouts();
		$this->data['entry_restore']=$this->language->get('entry_restore');
		$this->template = 'module/pagebuilder.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
		// this is first time when install  modules 
		if(!$this->config->get('pagebuilder'))
			$this->install();
		
		$this->response->setOutput($this->render());
	}
	
	public	function drawLayout(){
				
		$positions=array(
					'content_top'=>"content_top",
					"content_bottom"=>"content_bottom",
					"column_left"=>"column_left",
					"column_right"=>"column_right",
					"content_bottom_2"=>"content_bottom_2"
					);
		$layout_id=$_POST['layout_id'];

		$module_data = array();
		
		$this->load->model('setting/extension');
		$this->load->model('setting/setting');
		
		$extensions = $this->model_setting_extension->getExtensions('module');

		foreach ($extensions as $extension) {
			//echo "<pre>";
			//print_r($extension);
			
			$modules = $this->config->get($extension['code'] . '_module');
			if ($modules) {
				foreach ($modules as $module) {

					foreach ($positions as $key => $position) {
						if ($module['layout_id'] == $layout_id && $module['position'] == $position && $module['status']) {
							$module_data[$position][] = array(
								'code'       => $extension['code'],
								'sort_order' => $module['sort_order']
							);
						}
						if(isset($module_data[$position])){
							$sort_order = array(); 
							foreach ($module_data[$position] as $key => $value) {
								$sort_order[$key] = $value['sort_order'];
					 		}
							array_multisort($sort_order, SORT_ASC, $module_data[$position]);
						}
					}
				}
			}
		}
		echo json_encode($module_data);
		die;
	}
	public function updaterOrder(){
		
		if (!$this->user->hasPermission('modify', 'module/pagebuilder')) {
			return false;
		}
				
		$this->load->model('setting/setting');
		//echo "<pre>";
		//print_r($_POST);
		//die;
		if(isset($_POST['data']) && is_array($_POST['data'])){
			foreach ($_POST['data'] as $key => $value) {
				$module=$this->model_setting_setting->getSetting($value['group']);
				//echo "<pre>";
				//print_r($module);
				//die;
				$moduleKey=$value['group']."_module";
				$indexArray=$this->multidimensional_search($module[$moduleKey],array(
					'position'=>$value['position'],
					"layout_id"=>$value['layout_id'],
					"sort_order"=>$value['sort_order']
					));
				//change orders 
				$module[$moduleKey][$indexArray]['sort_order']=($key+1);
				// change positions 
				//if(isset($_POST['main_position']) && $_POST['main_position'] != $value['position'])
					$module[$moduleKey][$indexArray]['position']=$_POST['main_position'];
			//	echo "<pre> NEXT ";
			//	print_r($module);
				//die;
				$this->model_setting_setting->editSetting($value['group'], $module);
				sleep(1);
			}
		}
	}

	public function deleteModule(){
		
		if (!$this->user->hasPermission('modify', 'module/pagebuilder')) {
			return false;
		}
				
		$this->load->model('setting/setting');
		//echo "<pre>";
		//print_r($_POST);
		//die;
		if(isset($_POST['layout_id'])){
				$module=$this->model_setting_setting->getSetting($_POST['group']);
				//echo "<pre>";
				//print_r($module);
				//die;
				$moduleKey=$_POST['group']."_module";
				$indexArray=$this->multidimensional_search($module[$moduleKey],array(
					'position'=>$_POST['position'],
					"layout_id"=>$_POST['layout_id'],
					"sort_order"=>$_POST['sort_order']
					));
				//remove module
				unset($module[$moduleKey][$indexArray]);
				//echo "<pre> NEXT ";
				//print_r($module);
				//die;
				$this->model_setting_setting->editSetting($_POST['group'], $module);
				
			
		}
	}

	public function install(){
		$position=array('positions'=>
			array(
				'id'=>"content_top",
				'name'=>"Content Top",
				'col'=>1,
				'row'=>1,
				"size_x"=>5,
				"size_y"=>2
			),
			array(
				'id'=>"content_bottom",
				'name'=>"Content Bottom",
				'col'=>1,
				'row'=>6,
				"size_x"=>5,
				"size_y"=>2
			),
			array(
				'id'=>"content_bottom_2",
				'name'=>"Content Bottom 2",
				'col'=>1,
				'row'=>8,
				"size_x"=>5,
				"size_y"=>2
			),
			array(
				'id'=>"column_left",
				'name'=>"Column Left",
				'col'=>1,
				'row'=>3,
				"size_x"=>2,
				"size_y"=>3
			),
			array(
				'id'=>"column_right",
				'name'=>"Column Right",
				'col'=>4,
				'row'=>3,
				"size_x"=>2,
				"size_y"=>3
			)
		);
		$this->load->model('setting/setting');
		$this->model_setting_setting->editSetting('pagebuilder', array('pagebuilder'=>$position));
	}
	public function savePositions(){
	//	echo "<pre>";
	//	print_r($_POST);
		if (!$this->user->hasPermission('modify', 'module/pagebuilder')) {
			return false;
		}

		$this->load->model('setting/setting');
		$this->model_setting_setting->editSetting('pagebuilder', array('pagebuilder'=>$_POST["positions"]));
	
		//sleep(1);
	}
	public function getPositions(){
		echo  json_encode($this->config->get('pagebuilder'));
		die;
	}
	function multidimensional_search($parents, $searched) { 
		if (empty($searched) || empty($parents)) { 
			return false; 
		}
		foreach ($parents as $key => $value) { 
			$exists = true; 
			foreach ($searched as $skey => $svalue) { 
				$exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue); 
			}
		if($exists){ return $key; } 
		}
		return false; 
	}
	public function backup() {
		$this->language->load('tool/backup');
		if ($this->user->hasPermission('modify', 'tool/backup')) {
			$this->response->addheader('Pragma: public');
			$this->response->addheader('Expires: 0');
			$this->response->addheader('Content-Description: File Transfer');
			$this->response->addheader('Content-Type: application/octet-stream');
			$this->response->addheader('Content-Disposition: attachment; filename=' . date('Y-m-d_H-i-s', time()).'_backup.sql');
			$this->response->addheader('Content-Transfer-Encoding: binary');
			
			$this->load->model('tool/backup');
			$tableName=array(DB_PREFIX .'setting');
			$this->response->setOutput($this->model_tool_backup->backup($tableName));
		} else {
			$this->session->data['error'] = $this->language->get('error_permission');
			
			$this->redirect($this->url->link('module/pagebuilder', 'token=' . $this->session->data['token'], 'SSL'));			
		}
	}
	public function restore() {
		$this->language->load('module/pagebuilder');
		$this->load->model('tool/backup');
		if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->user->hasPermission('modify', 'tool/backup')) {
			if (is_uploaded_file($this->request->files['import']['tmp_name'])) {
				$content = file_get_contents($this->request->files['import']['tmp_name']);
			} else {
				$content = false;
			}
			
			if ($content) {
				$this->model_tool_backup->restore($content);
				
				$this->session->data['success'] = $this->language->get('text_success');
				
				$this->redirect($this->url->link('module/pagebuilder', 'token=' . $this->session->data['token'], 'SSL'));
			} else {
				$this->session->data['error'] = $this->language->get('error_empty');
			}
		}
	}
}
?>